package com.hp.bon.sgw.wh.channel.handler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.core.BuzProcessorManager;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.channel.SoapChannel;
import com.hp.bon.sgw.core.channel.handler.IAsynCallHandler;
import com.hp.bon.sgw.start.SpringContext;
import com.hp.bon.sgw.threads.TaskManager;
import com.hp.bon.sgw.wh.service.UserResourceConfigService;
import com.hp.bon.sgw.wh.utils.LogUtil;
import com.hp.bon.sgw.wh.utils.ResultCodeUtil;
import com.hp.ocs.diameter.message.Message;
import org.simpleframework.http.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

public class AccuUseQryHandle implements IAsynCallHandler {
	
	private static final Logger _log = LoggerFactory.getLogger(AccuUseQryHandle.class);
	private PrintStream printStream;
	private JSONObject jsonContent;
    private long startTime;
    private Request request;
    private UserResourceConfigService userResourceConfigService ;
	public AccuUseQryHandle(PrintStream printStream, JSONObject jsonContent, Request request, long startTime) {
		this.printStream = printStream;
		this.jsonContent = jsonContent;
        this.startTime = startTime;
        this.request = request;
	}

	@Override
	public int getProtocolType() {
		return 0;
	}

	@Override
	public void onCallResult(CallParam callParam) {
        jsonContent.put("jfEndTime",System.currentTimeMillis());
		XmlMessage ack = null;
		Object response = null;
		if (callParam.getResponse() != null) {
			response = callParam.getResponse();
		} else if (callParam.getRecvResponse() != null) {
			response = callParam.getRecvResponse();
		}
		if (response == null) {
			int _retcodeTmp = callParam.getRetCode() == 3002 ? 11202 : callParam.getRetCode();
			ack = SoapChannel.createERRAnwser(callParam.getSessionId(), _retcodeTmp, callParam.getResultMsg());
			callParam.setServiceResultCode(_retcodeTmp);// 11203
		} else {
			if (response instanceof Message) {// CCA -> XML
				ack = BuzProcessorManager.getInstance().convertMessageToAck(callParam);
			} else if (response instanceof XmlMessage) {
				ack = (XmlMessage) response;
			} else {
				_log.warn("unknown response type:" + callParam.getResponse().getClass().getName());
			}
		}
		try {
			String respXML="";
			try {
				respXML = convertResponseString(ack, callParam.getServiceResultCode());
			} catch (Exception e) {
                _log.info("=====respXML:Exception ",e);
			}

			byte[] resp = respXML.getBytes("UTF-8");
			ack.setLength(resp.length);
			ack.setMsgTime(System.currentTimeMillis());
			printStream.write(resp);
			printStream.close();
			callParam.setResponse(ack);
            //记录到日志
            LogUtil.saveLogToABM(request,respXML,startTime,jsonContent);
			TaskManager.taskProcess(callParam);
            _log.info("http response(returnBalance) " + respXML);

		} catch (UnsupportedEncodingException e) {
			_log.info("convertResponseString UnsupportedEncodingException error,msg=" + e.getMessage());
		} catch (IOException e) {
			_log.info("convertResponseString IOException,msg=" + e.getMessage());
		}
	}

	
	
	/**
	 * 从Message中解析出需要的数据，并拼接成json字符串
	 * @param answer
	 * @param serviceResultCode
	 * @return
	 */
	private String convertResponseString(XmlMessage ack, int serviceResultCode) {
		_log.info("AccuUseQryHandle serviceResultCode = {}", serviceResultCode);
        _log.info("===========service_result_code===============" + serviceResultCode);
		String response = "";
		Map<String, Object> data = new HashMap<String, Object>();
		if (serviceResultCode == 0) {
			response = ack.getDATA();
            String jf3_ratable_flag=jsonContent.getString("jf3_ratable_flag");
			if ( "1".equals(jf3_ratable_flag)){
			    //新流程不用解析
                try{
                    JSONObject responseJson=JSONObject.parseObject(response);
                    String resultCode=responseJson.getString("resultCode");
                    String resultMsg=responseJson.getString("resultMsg");
                    if("0".equals(resultCode)){
                        JSONArray offerInstInfoList=responseJson.getJSONArray("offerInstInfo");
                        if(offerInstInfoList == null || offerInstInfoList.size() == 0){
                            offerInstInfoList=new JSONArray();
                        }
                        for (int i = 0; i < offerInstInfoList.size(); i++) {
                            JSONObject jsonObject = offerInstInfoList.getJSONObject(i);
                            jsonObject.put("accuQryList",jsonObject.getJSONArray("AccuQryList"));
                            jsonObject.remove("AccuQryList");
                            JSONArray jsonArray = jsonObject.getJSONArray("accuQryList");
                            for (int j = 0; j < jsonArray.size(); j++) {
                                JSONObject jsonObject2 = jsonArray.getJSONObject(j);
                                jsonObject2.put("ownerType", "80A".equals(jsonObject2.getString("ownerType"))?1:2);
                                jsonObject2.put("initVal", jsonObject2.getLong("initVal"));
                                jsonObject2.put("accuVal", jsonObject2.getLong("accuVal"));
                                jsonObject2.put("usageVal", jsonObject2.getLong("usageVal"));
                                jsonObject2.put("accuTypeId", jsonObject2.getLong("accuTypeAttr"));
                                jsonArray.set(j,jsonObject2);
                            }
                            offerInstInfoList.set(i,jsonObject);
                        }
                        data.put("billingCycle", jsonContent.getLong("billingCycle"));
                        data.put("accNbr",jsonContent.getString("accNbr"));
                        data.put("destinationAttr",jsonContent.getString("destinationAttr"));
                        data.put("offerInstInfo",offerInstInfoList);//套餐信息组
                        data.put("resultCode","0");//业务级的结果代码
                        data.put("resultMsg","SUCCESS");//错误信息 ，对业务校验错，填出出错的原始avp信息
                    }else{
                        data.put("resultCode", resultCode);
                        data.put("resultMsg", resultMsg);
                    }
                }catch (Exception e){
                    _log.error("========AccuUseQryHandle.convertResponseString.Exception:",e);
                    data.put("resultCode", "-1");
                    data.put("resultMsg", "查询失败");
                }
            }
		}else {
			data.put("resultCode", "-1");
			data.put("resultMsg", "查询失败");
		}
        userResourceConfigService = SpringContext.getApplicationContext().getBean(UserResourceConfigService.class);
        String newCode = ResultCodeUtil.updateResultCode(data.get("resultCode"), userResourceConfigService.getValue("api_resultCode"), userResourceConfigService.getValue("api_defaultResult"));
        data.put("resultCode", newCode);
        Gson gson = new Gson();
		response = gson.toJson(data);
		return response;
	}
	
}
